package bepviet.android.ui.fragment;

import java.util.ArrayList;

import bepviet.android.engine.DataAdapter;
import bepviet.android.ui.PreparedMail;
import bepviet.android.engine.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class TextContent extends Activity implements OnGestureListener {
	private TextView text1, text2, text3, text4, txtback, txttitle;
	private ViewFlipper viewFlipper;
	private String s1,s2,s3,s4, contentmail;
	private String ThucHien,GioiThieu,NguyenLieuChuanBi,LoaiMonAn,XuatXu,TenMonAn;
	private DataAdapter dataAdapter;	
	private LinearLayout ln; 
	private GestureDetector detector;
	private ImageView imageView,imgmail;	
	private byte[] blob;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.text_content);
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);		
		View view = inflater.inflate(R.layout.text_intro,null);
		ln = new LinearLayout(this);
		text1 = (TextView)view.findViewById(R.id.txtIntro);
		text2 = new TextView(this);
		text3 = new TextView(this);
		text4 = new TextView(this);
		
		txtback = (TextView)findViewById(R.id.txtback_content);
		txttitle = (TextView)findViewById(R.id.txttitle_content);
		detector = new GestureDetector(this);
		imageView = (ImageView)view.findViewById(R.id.imageview);
		imgmail = (ImageView)findViewById(R.id.iconmail);
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();		
		//viewFlipper = (ViewFlipper) findViewById(R.id.view_switcher);
		dataAdapter = new DataAdapter(this);	
		Cursor c ;		
		dataAdapter.OpenDataBase();	
		
		
		
		try{
			c = dataAdapter.QueryData("Select * from MonAn where MaMonAn = '"+bundle.getInt("Ma")+"'");
			if(c != null){
				if(c.moveToFirst()){
					do{
						blob = c.getBlob(c.getColumnIndex("HinhAnh"));
						ThucHien = c.getString(c.getColumnIndex("ThucHien"));
						GioiThieu =  c.getString(c.getColumnIndex("GioiThieu"));
						NguyenLieuChuanBi =  c.getString(c.getColumnIndex("NguyenLieuChuanBi"));
					}while(c.moveToNext());
				}
			}
		}catch(Exception ex){}
		
		try{
			c = dataAdapter.QueryData("Select * from LoaiMonAn where MaLoai = " +
							"(Select MaLoai from MonAn where MaMonAn = '"+bundle.getInt("Ma")+"')");
			if(c != null){
				if(c.moveToFirst()){
					do{
						LoaiMonAn = c.getString(c.getColumnIndex("TenLoai"));
					}while(c.moveToNext());
				}
			}
		}catch(Exception ex){}
		
		try{
			c = dataAdapter.QueryData("Select * from XuatXu where MaXuatXu = " +
							"(Select MaXuatXu from MonAn where MaMonAn = '"+bundle.getInt("Ma")+"')");
			if(c != null){
				if(c.moveToFirst()){
					do{
						XuatXu = c.getString(c.getColumnIndex("VungXuatXu"));
					}while(c.moveToNext());
				}
			}
		}catch(Exception ex){}
		ArrayList<String> NguyenLieu = null;		
		try{
			c = dataAdapter.QueryData(" Select  TenNguyenLieu from NguyenLieu N " +
					"Join MonAn_NguyenLieu MN on MN.MaNguyenLieu = N.MaNguyenLieu " +
					"Join MonAn M on M.MaMonAn = MN.MaMonAn and M.MaMonAn = '"+bundle.getInt("Ma")+"' " +
					"Group by TenNguyenLieu Having count(distinct M.MaMonAn)=1");
			if(c != null){
				NguyenLieu = new ArrayList<String>();
				if(c.moveToFirst()){
					do{
						NguyenLieu.add(c.getString(c.getColumnIndex("TenNguyenLieu")));
					}while(c.moveToNext());
				}
			}
		}catch(Exception ex){}
		
		for(int i =0;i< NguyenLieu.size();i++){
			String w = NguyenLieu.get(i)+"\n";
		}
		
		
		TenMonAn = bundle.getString("Ten");		
		s1 = " -Tên Món Ăn : "+TenMonAn+"\n -Loại Món Ăn : "+LoaiMonAn+"\n -Xuất Xứ : "+ XuatXu;
		s2= " GIỚI THIỆU MÓN ĂN :\n"+GioiThieu;
		s3 = " NGUYÊN LIỆU CHUẨN BỊ :\n"+NguyenLieuChuanBi;
		s4 = " THỰC HIỆN :\n"+ThucHien;	
		contentmail = s1+ "\n\n" + s2 + "\n\n" + s3 + "\n\n" + s4;
			
		text2.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		text3.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		text1.setPadding(5, 5, 5, 5); text1.setTextSize(17f);
		text2.setPadding(5, 5, 5, 5); text2.setTextSize(17f);
		text3.setPadding(5, 5, 5, 5); text3.setTextSize(17f);
		text4.setPadding(5, 5, 5, 5); text4.setTextSize(17f);
		
//		text1.setMovementMethod(new ScrollingMovementMethod().getInstance());
//		text2.setMovementMethod(new ScrollingMovementMethod().getInstance());
		text4.setMovementMethod(new ScrollingMovementMethod().getInstance());
			
		
		imageView.setImageDrawable(convertBlobToBitmap(blob));
		imageView.setPadding(10, 10, 10, 10);
		
		
				
		text1.setText(s1);	
		text2.setText(s2);
		text3.setText(s3);
		text4.setText(s4);
		txttitle.setText(TenMonAn);
		ln.addView(view);
		viewFlipper.addView(ln);
		viewFlipper.addView(text2);
		viewFlipper.addView(text3);
		viewFlipper.addView(text4);	
		txtback.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();				
			}
		});
		
		imgmail.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(TextContent.this, PreparedMail.class);
				Bundle bundle = new Bundle();
				bundle.putString("contentmail", contentmail);
				intent.putExtras(bundle);
				startActivity(intent);		
				
			}
		});
		
	}

	
	public BitmapDrawable convertBlobToBitmap(byte[] blobByteArray) {       
        Bitmap tempBitmap=null;        
        if(blobByteArray!=null)
        tempBitmap = BitmapFactory.decodeByteArray(blobByteArray, 0, blobByteArray.length);
        int width = tempBitmap.getWidth();
        int height = tempBitmap.getHeight();
        
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) 400) / width;
        float scaleHeight = ((float) 200) / height;
        matrix.postScale(scaleWidth, scaleHeight);       
        matrix.postRotate(0); // rotate the Bitmap
        
        Bitmap resizingBitmap = Bitmap.createBitmap(tempBitmap,0,0,width,height,matrix,true); // recreate the new Bitmap
        
        BitmapDrawable bmd = new BitmapDrawable(resizingBitmap);
        
        return bmd;
    }
	
	
	
	// =======================================================================================

	private Animation InfromRight() {
		Animation inFromRight = new TranslateAnimation(
		Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT,0.0f,
		Animation.RELATIVE_TO_PARENT, 0.0f,	 Animation.RELATIVE_TO_PARENT, 0.0f
		);
		inFromRight.setDuration(500);	
		inFromRight.setInterpolator(new AccelerateInterpolator());
		return inFromRight;
	}

	private Animation OuttoLeft() {
		Animation outtoLeft = new TranslateAnimation(
		Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
		Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
		);
		outtoLeft.setDuration(500);
		outtoLeft.setInterpolator(new AccelerateInterpolator());
		return outtoLeft;
	}

	 private Animation InfromLeft(){
		 Animation inFromLeft = new TranslateAnimation(
		 Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT,0.0f,
		 Animation.RELATIVE_TO_PARENT, 0.0f,  Animation.RELATIVE_TO_PARENT, 0.0f
		 );
		 inFromLeft.setDuration(500);	
		 inFromLeft.setInterpolator(new AccelerateInterpolator());
		 return inFromLeft;
	 }
	
	 private Animation OuttoRight(){
		 
		 Animation outtoRight = new TranslateAnimation(
		 Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,
		 Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
		 );
		 outtoRight.setDuration(500);
		 outtoRight.setInterpolator(new AccelerateInterpolator());
		 return outtoRight;
	 }

	// =======================================================================================
	 
	 	  
	 
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return detector.onTouchEvent(event);
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if(e1.getX() - e2.getX() > 0){
			viewFlipper.setInAnimation(InfromRight());
			viewFlipper.setOutAnimation(OuttoLeft());
			viewFlipper.showNext();
		}else{
			viewFlipper.setInAnimation(InfromLeft());
			viewFlipper.setOutAnimation(OuttoRight());
			viewFlipper.showPrevious();
		}			
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

}
